package com.xunqi.shiro.config;

import com.xunqi.shiro.pojo.User;
import com.xunqi.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

public class MyRealm extends AuthorizingRealm {

    //SLJ4J日志门面
    Logger logger = LoggerFactory.getLogger(MyRealm.class);

    @Resource
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("身份认证：MyShiroRealm.doGetAuthenticationInfo");

        //获取用户输入的账号
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;

        String usrName = token.getUsername();
        String usrPassword = new String(token.getPassword());
        System.out.println("usrName：" + usrName);
        System.out.println("usrPassword：" + usrPassword);

        //通过username从数据库中查找User对象，如果找到，没找到
        //实际情况中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        User user = userService.findByUserName(usrName);
        System.out.println("------>>user=" + user);

        if (user == null) {
            throw new UnknownAccountException("账号不存在");
        } else if (!user.getPassword().equals(usrPassword)) {
            throw new IncorrectCredentialsException("密码不正确");
        }

        //认证信息
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user,   //用户
                user.getPassword(),  //密码
                getName()       //realm name
        );

        return authenticationInfo;
    }
}
